using System.Collections.Generic;
using Kayac;
using UnityEngine;
using EzySlice;
using Unity.VisualScripting;
using Unity.Mathematics;
public class EnemyPart : MonoBehaviour
{
	public float Deflectprobability = 0.2f;
	public bool isDeflected = true;
	private int horizontalDivision;

	[SerializeField]
	private int roundingDivision;

	[SerializeField]
	private float roundingHeightRatio;

	[SerializeField]
	private float initialHp;

	[SerializeField]
	private float velocitySmoothing;

	[SerializeField]
	private float shockMultiplier;

	[SerializeField]
	private float impactDamageFactor;

	[SerializeField]
	private float damageRecovery;

	[SerializeField]
	private float impactCutTreshold;

	[SerializeField]
	private float impactSeparatingForce;

	[SerializeField]
	private Vector2 uRange;

	[SerializeField]
	private Vector2 vRange;

	[SerializeField]
	private Vector2 cutFaceUv;

	[SerializeField]
	private bool smoothMesh;

	[SerializeField]
	private float torusRadiusRatio;

	[SerializeField]
	private SoundMaterial soundMaterial;

	[SerializeField]
	private Material deathMaterialOverride;

	[SerializeField]
	private ArticulationBody body;

	[SerializeField]
	private Rigidbody rBody;

	[SerializeField]
	private ConfigurableJoint joint;

	[SerializeField]
	private MeshCollider collider;

	[SerializeField]
	private MeshFilter meshFilter;

	[SerializeField]
	private Cannon holdingCannon;

	private Enemy owner;

	private Model model;

	private Mesh dynamicMesh;

	public float hp;

	private int cutCount;

	private Vector3 lastVelocity;

	private bool splitted;

	private List<BulletBase> hitBullets = new List<BulletBase>();

	public Model Model => null;

	public float InitialSurfaceArea { get; private set; }

	public float CurrentSurfaceArea { get; private set; }

	public Vector3 SmoothedVelocity { get; private set; }

	public Enemy Owner => null;

	public bool Alive => false;

	public float Hp
	{
		get => hp;
		private set
		{
			hp = value;
			if (hp <= 0f)
			{
			}
		}
	}

	public Vector3 Velocity => default(Vector3);

	public Vector3 AngularVelocity => default(Vector3);

	public Vector3 WorldCenterOfMass => default(Vector3);

	public Transform BodyTransform => null;

	public float Mass => 0f;
	public static void ManualStartRecursive(Transform root, Enemy owner)
	{
	}

	public static float SumSurfaceAreaRecursive(Transform node)
	{
		return 0f;
	}
	public void Start()
	{
		hp = initialHp;
	}
	public void ManualStart(Enemy owner)
	{
		this.owner = owner;
		hp = initialHp;
	}

	public void ManualFixedUpdate(float deltaTime)
	{
	}

	public void ManualUpdate(float deltaTime)
	{
	}

	public void AddTorque(Vector3 torque, ForceMode mode = ForceMode.Force)
	{
		if (body != null && body.isActiveAndEnabled)
		{
			body.AddTorque(torque, mode);
		}
		else if (rBody != null && rBody)
		{
			rBody.AddTorque(torque, mode);
		}
	}

	public void AddForce(Vector3 force, ForceMode mode = ForceMode.Force)
	{
		if (body != null && body.isActiveAndEnabled)
		{
			body.AddForce(force, mode);
		}
		else if (rBody != null && rBody)
		{
			rBody.AddForce(force, mode);
		}
	}

	public void AddForceAtPosition(Vector3 force, Vector3 position, ForceMode mode = ForceMode.Force)
	{
		if (body != null && body.isActiveAndEnabled)
		{
			Vector3 torque = Vector3.Cross(position - body.worldCenterOfMass, force);
			body.AddForce(force, mode);
			body.AddTorque(torque, mode);
		}
		else if (rBody != null && rBody)
		{
			rBody.AddForceAtPosition(force, position, mode);
		}
	}

	public void OnDie()
	{
		if (owner != null)
		{
			SetDeathMaterial();
			owner.OnDestroyPart(this);
		}
	}

	public float CalcFarestDistance(Vector3 from)
	{
		return 0f;
	}

	public float GetBoundingRadius()
	{
		return 0f;
	}

	public Vector3 GetAnchorPosition()
	{
		return default(Vector3);
	}

	public void RegisterHitBullet(BulletBase bullet)
	{
		hitBullets.Add(bullet);
	}

	public void UnregisterHitBullet(BulletBase bullet)
	{
		if (hitBullets != null)
			hitBullets.Remove(bullet);
	}

	public bool IsBulletRegistered(BulletBase bullet)
	{
		return false;
	}

	public float Damage(BulletBase bullet, float damage, out EnemyPart newSubPart)
	{
		newSubPart = null;
		hp -= damage;
		if (hp > 0f)
			RegisterHitBullet(bullet);
		PostDamage(bullet, damage, Enemy.DamageType.Impale);
		return damage;
	}

	public void PostDamage(BulletBase bullet, float damage, Enemy.DamageType damageType)
	{
	}

	public void CutByImpaled()
	{
	}

	// private void OnTriggerEnter(Collider collision)
	// {

	// 	if (collision.transform.TryGetComponent<BulletBase>(out BulletBase bullet))
	// 	{
	// 		if (hp <= 0f)
	// 		{
	// 			Cut(bullet);
	// 			collision.enabled = false;
	// 		}
	// 	}
	// }
	private void OnCollisionEnter(Collision collision)
	{
		collision.transform.TryGetComponent<Unbreakable>(out Unbreakable unbreakable);
		if (unbreakable != null)
		{
			AudioManager.Instance.PlayOnShot((int)ClipType.diaodishang);
		}
	}
	private void ApplyImpactDamage(Collision collision)
	{
	}

	private void SetDynamic()
	{
	}

	private void OnDieRecursive(Transform node)
	{
	}
	private EnemyPart TryCut(mypanel worldPlane, float separatingForce, out bool mainInFront)
	{
		mainInFront = false;
		return Split(worldPlane);
	}
	public EnemyPart Cut(BulletBase bullet)
	{
		bool mainInFront;
		EnemyPart subPart = TryCut(new mypanel(bullet.transform.position, bullet.transform.up.normalized), impactSeparatingForce, out mainInFront);
		for (int i = 0; i < hitBullets.Count; i++)
		{
			BulletBase hitBullet = hitBullets[i];
			if (hitBullet != null)
			{
				UnregisterHitBullet(hitBullet);
				// 处理已注册的子弹
				hitBullet.Kill();
			}
		}
		subPart?.OnDie();
		return subPart;
	}
	private static void MoveRegisteredBulletsInBack(EnemyPart mainPart, EnemyPart subPart, UnityEngine.Plane plane, bool mainInFront)
	{
	}

	private void ManualStartForCutSub(EnemyPart enemyPart, Enemy owner)
	{
		hp = 0.01f;
		this.owner = owner;
		isDeflected = enemyPart.isDeflected;
	}

	private void SetDeathMaterial()
	{
		if (owner.DeathMaterial != null)
		{
			if (meshFilter != null && meshFilter.sharedMesh != null)
			{
				meshFilter.GetComponent<Renderer>().material = owner.DeathMaterial;
			}
		}
	}

	private void ManualStartForCutRoot(Enemy owner)
	{
		this.hp = 0.01f;
	}

	private void ManualStartRecursiveForCut(Transform src, Transform dst)
	{
	}

	private static void RemoveCutBodies(EnemyPart part, UnityEngine.Plane worldPlane, Enemy owner, bool removeBack)
	{
	}

	private static bool RemoveCutBodiesSub(Transform node, UnityEngine.Plane worldPlane, Enemy owner, bool nearestPartWasCut, bool removeBack)
	{
		return false;
	}

	private void ApplyMesh()
	{

	}

	private void UpdateCollider()
	{

	}

	private void SetMaxAngularVelocity(float maxAngularVelocity)
	{
		if (rBody != null)
			rBody.maxAngularVelocity = maxAngularVelocity;
	}

	private void SetVelocity(Vector3 velocity)
	{
		if (rBody != null)
			rBody.velocity = velocity;
	}

	private void SetAngularVelocity(Vector3 angularVelocity)
	{
		if (rBody != null)
			rBody.angularVelocity = angularVelocity;
	}

	private void SetMass(float mass)
	{
	}
	public EnemyPart Split(mypanel plane)
	{
		SlicedHull hull = meshFilter.gameObject.Slice(plane.position, plane.normal);
		if (hull == null)
		{
			Debug.LogWarning("切割失败，hull为null");
			return (EnemyPart)null;
		}

		Transform originalTransform = this.transform;
		GameObject originalMeshGameObject = meshFilter.gameObject;
		GameObject lower = hull.CreateLowerHull(meshFilter.gameObject, Main.Instance.cross);
		GameObject upper = hull.CreateUpperHull(meshFilter.gameObject, Main.Instance.cross);

		if (lower == null || upper == null)
		{
			Debug.LogWarning("切割失败，upper或lower为null");
			return (EnemyPart)null;
		}

		GameObject lowerParent = new GameObject("LowerPart");
		GameObject upperParent = new GameObject("UpperPart");
		Debug.Log("切割成功生成新网格");
		lowerParent.transform.SetParent(Main.Instance.level.transform, false);
		upperParent.transform.SetParent(Main.Instance.level.transform, false);
		float separateDistance = 0.05f; // 可根据模型大小动态调整
		Vector3 offset = plane.normal.normalized * separateDistance;

		lowerParent.transform.SetPositionAndRotation(originalTransform.position - offset, originalTransform.rotation);
		lowerParent.transform.localScale = originalTransform.localScale;
		lower.transform.SetParent(lowerParent.transform, true);
		lower.transform.localPosition = meshFilter.transform.localPosition; // 保持相对于父对象的位置
		lower.transform.localRotation = Quaternion.identity; // 保持相对于父对象的旋转
		lower.transform.localScale = meshFilter.transform.localScale;
		var lowerPart = lowerParent.AddComponent<EnemyPart>();
		lowerPart.meshFilter = lower.GetComponent<MeshFilter>();
		lowerPart.collider = lower.AddComponent<MeshCollider>();
		lowerPart.collider.material = meshFilter.GetComponent<MeshCollider>().material;
		lowerPart.AddComponent<Rigidbody>();
		lowerPart.collider.convex = true;
		upperParent.transform.SetPositionAndRotation(originalTransform.position + offset, originalTransform.rotation);
		upperParent.transform.localScale = originalTransform.localScale;
		upper.transform.SetParent(upperParent.transform, true);
		upper.transform.localPosition = meshFilter.transform.localPosition;
		upper.transform.localRotation = Quaternion.identity; // 保持相对于父对象的旋转
		upper.transform.localScale = meshFilter.transform.localScale;
		var upperPart = upperParent.AddComponent<EnemyPart>();
		upperPart.meshFilter = upper.GetComponent<MeshFilter>();
		upperPart.collider = upper.AddComponent<MeshCollider>();
		upperPart.collider.material = meshFilter.GetComponent<MeshCollider>().material;
		upperPart.collider.convex = true;
		upperPart.AddComponent<Rigidbody>();
		Vector3 connectedPos = joint != null && joint.connectedBody != null
	   ? joint.connectedBody.transform.position
	   : transform.position;
		Vector3 lowerCenter = lower.GetComponent<MeshRenderer>()?.bounds.center ?? lower.transform.position;
		Vector3 upperCenter = upper.GetComponent<MeshRenderer>()?.bounds.center ?? upper.transform.position;
		float distToLower = Vector3.Distance(lowerCenter, connectedPos);
		float distToUpper = Vector3.Distance(upperCenter, connectedPos);
		EnemyPart mainPart = null;
		EnemyPart subPart = null;
		if (distToLower < distToUpper)
		{
			lower.transform.SetParent(this.transform, true);
			this.meshFilter = lower.GetComponent<MeshFilter>();
			this.collider = lower.GetComponent<MeshCollider>();
			this.transform.SetPositionAndRotation(lowerParent.transform.position, lowerParent.transform.rotation);
			this.transform.localScale = lowerParent.transform.localScale;
			Destroy(lowerParent);
			ManualStartForCutRoot(owner);
			upperPart.ManualStartForCutSub(this, owner);
			lower.name = "View";
			subPart = upperPart;
		}
		else
		{
			// upper为主部分
			upper.transform.SetParent(this.transform, true);
			this.meshFilter = upper.GetComponent<MeshFilter>();
			this.collider = upper.GetComponent<MeshCollider>();
			this.transform.SetPositionAndRotation(originalTransform.position, originalTransform.rotation);
			this.transform.localScale = originalTransform.localScale;
			Destroy(upperParent);
			ManualStartForCutRoot(owner);
			lowerPart.ManualStartForCutSub(this, owner);
			upper.name = "View";
			subPart = lowerPart;
		}
		Destroy(originalMeshGameObject);
		mainPart = this;
		if (rBody != null)
		{
			rBody.mass *= 0.5f;
		}
		if (joint != null)
		{
			Destroy(joint);
			mainPart.OnDie();
			subPart.OnDie();
		}
		else
		{
			UpdateJointsAfterCut(mainPart);
		}
		mainPart.GetComponent<Rigidbody>().AddExplosionForce(2f, originalTransform.position, 2f, 1f, ForceMode.Impulse);
		subPart.GetComponent<Rigidbody>().AddExplosionForce(2f, originalTransform.position, 2f, 1f, ForceMode.Impulse);
		return subPart;
	}
	private static void UpdateJointsAfterCut(EnemyPart mainPart)
	{
		mainPart.OnDie();
		foreach (Transform child in mainPart.transform)
		{
			var enemyPart = child.GetComponent<EnemyPart>();
			if (enemyPart != null)
			{
				if (enemyPart.joint != null)
				{
					if (true)
					{
						Destroy(enemyPart.joint);
					}
				}
				enemyPart.OnDie();
			}
		}
		bool IsBoundsIntersect(MeshFilter meshA, MeshFilter meshB)
		{
			return meshA.GetComponent<Renderer>().bounds.Intersects(meshB.GetComponent<Renderer>().bounds);
		}
	}
}